<template>

  <el-dialog
      v-model="computedDialogVisible"
      title="新增信封模板"
      width="30%"
  >
    <el-form label-width="120px">
      <el-form-item label="模板名称">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="封面">
        <div class="upload-section">
          <el-upload
              action="https://jsonplaceholder.typicode.com/posts/"
              :http-request="coverUpload"
              :show-file-list="false"
              limit="1"
          >
            <el-button type="primary">上传封面</el-button>
          </el-upload>
          <el-image class="cover" fit="cover" shape="square" style="width: 100px;height: 100px" :src="formData.picture"
                    v-if="formData.picture"></el-image>
        </div>
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number v-model="formData.price" :precision="2" :step="0.1" :max="10"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="computedDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import {computed, reactive} from "vue";
import {Template} from "@/typings";
import {ElMessage} from "element-plus";
import client from "@/utils/oss";
import {saveTemplate} from "@/api/post/template";

const props = defineProps({dialogVisible: {type: Boolean, default: false}})
const emits = defineEmits(['update:dialog-visible', 'submit'])
let formData = reactive<Template>({})
let computedDialogVisible = computed({
  get: () => {
    return props.dialogVisible
  },
  set: (value) => {
    emits('update:dialog-visible', value)
  }
})
const coverUpload = (params: any) => {
  let file = params.file as File
  uploadFile(file)
}
const uploadFile = async (file: File) => {
  let filename = new Date().getTime() + file.name
  let res = await client.put(filename, file)
  await client.putACL(filename, 'public-read');
  formData.picture = res.url
}
const handleConfirm = () => {
  saveTemplate(formData).then(res => {
    if (res == true) {
      ElMessage.success({message: '添加成功'})
      computedDialogVisible.value = false
      emits('submit')
    }
  })
}
</script>

<style lang="scss" scoped>
.upload-section {
  .cover {
    margin-top: 20px;
  }
}
</style>